<!--suppress ALL -->
<template>
  <div class="wrap wrap_detail" :class="{phone_x: iphonex}">
    <div class="mod_head_pic">
      <img class="head_pic" :src="info.r_thumbnail" alt="" mode="aspectFill" />
    </div>
    <div class="mod_headline">
      <div class="title">{{info.r_title}}</div>
      <div class="desc">
        <div v-html="info.r_assist_info"></div>
      </div>
    </div>

    <div :class="{none:isBuyIOS}">
      <div class="mod_box mod_box_explain" :class="{none: audio.length === 0}">
        <div class="mod_hd">
          <div class="title">讲解</div>
          <div class="mod_action" :class="{none: audioBuyInfo.show}">
            <div class="onplaying">连续播放</div>
            <Index :value="autoplayFlag" @changeSwitch="changeSwitch"></Index>
            <!--<switch :checked="autoplayFlag" @change="changeNow('switchItem', $event)"></switch>-->
          </div>
        </div>
        <div class="mod_bd">
          <div class="mod_explain">
            <div v-for="(item, index) in audio"
                 :key="item.goods_id"
                 class="explain_item"
                 :class="{active : item.is_have === 1, 'playing': item.playing, 'none': (index > 4 && hideMoreAudio) }"
                 @click="playAudio(item, index)">
              <div class="title">{{item.ssm_title}}</div>
              <div class="voice_block">
                <div class="iconfont" :class="{'icon-zspause': item.playing, 'icon-zsplay ': !item.playing}"></div>
                <div class="voice_progress" :id="'content_' + index">
                  <div class="progress_current" :style="{ width: item.progress + '%'}">
                    <div class="progress_btn"
                         :id="'thumb_' + index"
                         @touchstart="start($event, item, index)"
                         @touchmove="move($event, item, index)"
                         @touchend="end($event, item, index)"
                         @touchcancel="end($event, item, index)"></div>
                  </div>
                </div>
                <div class="voice_text">{{item.duration}}</div>
                <!-- <img src="/static/img/wave.png" alt="" class="icon_wave icon_wave_png"> -->
                <img src="/static/img/wave2.gif" alt="" class="icon_wave icon_wave_gif">
                <div class="iconfont icon-zssound"></div>
              </div>
            </div>
            <div v-if="audio.length > 5" class="btn_fold" @click="showMoreAudio">
              <span v-if="hideMoreAudio">查看全部<i class="iconfont icon-zsunfold"></i></span>
              <span v-else>收起<i class="iconfont icon-zspickup"></i></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_intro" :class="{none: !info.r_info}">
      <div class="mod_hd">
        <div class="title">简介</div>
      </div>
      <div class="mod_bd">
        <div class="mod_intro" :class="{open: !hideMoreDesc, fold: introFold}">
          <div class="intro_content" id="intro_content">
            <div v-html="info.r_info"></div>
            <span class="btm_mask"></span>
          </div>
          <div class="btn_fold"  @click="showMoreDesc">
            <span v-if="hideMoreDesc">展开全部<i class="iconfont icon-zsunfold"></i></span>
            <span v-else>收起<i class="iconfont icon-zspickup"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import fly from '@/utils/fly'
  import { getOpenid, getUnionid } from '@/utils/login'
  import { reportData } from '@/utils/report'
  import Index from '../btnswitch/index'

  const backgroundAudioManager = wx.getBackgroundAudioManager()
  const dataResArr = []

  export default {
    components: { Index },
    data () {
      return {
        isShow: false,
        isBuyIOS: false,
        banner_img: [],
        isJJ: false,
        autoplayFlag: false,
        info: {},
        audio: [],
        current: -1,
        hideMoreAudio: true,
        infoRelevant: [],
        goodsTicket: [],
        audioBuyInfo: {
          show: false,
          id: 0,
          price: 0
        },
        showAudioBuyLayer: false,
        hideMoreDesc: true,
        resId: '',
        introFold: false,
        relation_series: []
      }
    },
    computed: {
    },
    methods: {
      changeSwitch (checked) {
        console.log('连续播放:' + checked)
        this.autoplayFlag = checked
      },
      playAudio (item, index) {
        // let that = this
        if (index > this.audio.length) {
          backgroundAudioManager.destroy()
          return
        }
        if (item == null || item === '') {
          item = this.audio[index]
        }
        if (item.is_have !== 1) {
          return
        }
        if (this.current !== index || !backgroundAudioManager.src) {
          if (this.current !== -1) {
            let prev = this.audio[this.current]
            prev.playing = false
            prev.disabledDrag = true
            prev.progress = 0
            prev.duration = this.calcTime(prev.duration_s || 0)
          }
          this.current = index
          backgroundAudioManager.title = item.ssm_title
          backgroundAudioManager.src = item.audio_url
          backgroundAudioManager.epname = this.resId + '-' + this.current
          this.$root.$mp.appOptions._audioInfo = {
            title: item.ssm_title,
            resId: this.resId,
            current: this.current
          }
        } else {
          if (item.playing) {
            backgroundAudioManager.pause()
          } else {
            backgroundAudioManager.play()
          }
        }
      },
      calcTime (num) {
        let res = ('0' + Math.floor(num / 60)).slice(-2) + ':' + ('0' + Math.ceil(num % 60)).slice(-2)
        return res
      },
      boundingClientRect (id) {
        return new Promise((resolve, reject) => {
          let query = wx.createSelectorQuery()
          query.select('#' + id).boundingClientRect(rect => {
            resolve(rect)
          }).exec()
        })
      },
      async getThumbPosition (i) {
        const contentBox = await this.boundingClientRect('content_' + i)
        const thumbBox = await this.boundingClientRect('thumb_' + i)
        return {
          left: thumbBox.left - contentBox.left,
          top: thumbBox.top - contentBox.top,
          thumbBoxLeft: thumbBox.left
        }
      },
      async start (event, item, index) {
        if (item.disabledDrag) return
        const position = await this.getThumbPosition(index)
        const thumbClickDetalX = event.clientX - position.thumbBoxLeft
        item.dragState = {
          thumbStartLeft: position.left,
          thumbStartTop: position.top,
          thumbClickDetalX: thumbClickDetalX
        }
      },
      async move (event, item, index) {
        if (item.disabledDrag) return

        const contentBox = await this.boundingClientRect('content_' + index)
        const deltaX = event.pageX - contentBox.left - item.dragState.thumbStartLeft - item.dragState.thumbClickDetalX
        const stepCount = 100
        const newPosition = (item.dragState.thumbStartLeft + deltaX) - (item.dragState.thumbStartLeft + deltaX) % (contentBox.width / stepCount)
        let newProgress = newPosition / contentBox.width
        if (newProgress < 0) {
          newProgress = 0
        } else if (newProgress > 1) {
          newProgress = 1
        }
        let progress = Math.round(newProgress * 100)
        item.progress = progress
      },
      end (event, item, index) {
        if (item.disabledDrag) return
        item.dragState = null
        backgroundAudioManager.seek(item.duration_s * item.progress / 100)
        backgroundAudioManager.play()
      },
      showMoreAudio () {
        if (this.hideMoreAudio) {
          this.hideMoreAudio = false
        } else {
          this.hideMoreAudio = true
        }
      },
      gotoRes (item) {
        wx.navigateTo({
          url: '/pages/detail/main?id=' + item.r_id
        })
      },
      gotoGoods (item) {
        if (item.gt_id === 3) {
          wx.navigateTo({
            url: '/pages/detail/main?id=' + item.r_id
          })
        } else {
          wx.navigateTo({
            url: '/pages/goods-detail/main?id=' + item.goods_id
          })
        }
      },
      buyAudio (id) {
        this.showAudioBuyLayer = true
        reportData({
          funcx: '景点-语音付费弹窗',
          keyx: id
        })
      },
      closeAudioBuyLayer () {
        this.showAudioBuyLayer = false
      },
      showMoreDesc () {
        if (this.hideMoreDesc) {
          this.hideMoreDesc = false
        } else {
          this.hideMoreDesc = true
        }
      },
      async loadData () {
        var that = this
        wx.showLoading({
          title: '加载中'
        })
        let openid = await getOpenid()
        let res = await fly.post(`Resource/get?r_id=${this.resId}&wx_openid=${openid}`)
        wx.hideLoading()
        if (res && res.code === 200 && res.data) {
          this.info = res.data.info
          this.info.r_info = this.info.r_info.replace(/<img/gi, '<img style="max-width:100%;height:auto;margin: 15px auto;" ')

          // 渲染音频
          res.data.goods_audio.forEach((item, j) => {
            item.duration = this.calcTime(item.playtime || 0)
            item.progress = 0
            item.playing = false
            item.disabledDrag = true

            item.is_have = 1
          })

          this.audio = res.data.goods_audio
          // 已经购买过了
          this.audioBuyInfo.show = false
          // 附近景点
          this.infoRelevant = res.data.info_relevant
          this.relation_series = res.data.relation_series || []
          // 商品
          this.goodsTicket = res.data.goods_ticket

          // 简介高度计算
          setTimeout(function () {
            wx.createSelectorQuery().select('#intro_content').boundingClientRect(
              function (rect) {
                if (rect.height >= 96) {
                  that.introFold = true
                } else {
                  that.introFold = false
                }
              }
            ).exec()
          }, 100)
        } else {

        }
      },
      async signInRes () {
        if (this.info.is_have_sign_in === 1) {
          return
        }
        let openid = await getOpenid()
        let rid = this.resId
        let res = await fly.post(`User/signIn?r_id=${rid}&wx_openid=${openid}`)
        if (res && res.code === 200 && res.data) {
          this.info.is_have_sign_in = 1
          wx.showToast({
            title: '签到成功'
          })
          // 设置个全局变量，里面签到影响外面
          this.$root.$mp.appOptions['_resSign_' + rid] = true
        } else {

        }
      },
      initBackAudio () {
        let audioInfo = this.$root.$mp.appOptions._audioInfo

        if (audioInfo === undefined && backgroundAudioManager && backgroundAudioManager.epname) {
          let epname = backgroundAudioManager.epname.split('-')
          audioInfo = {
            resId: epname[0],
            current: epname[1]
          }
        }

        if (audioInfo && !backgroundAudioManager.paused && audioInfo.resId === this.resId) {
          this.current = audioInfo.current
          if (this.audio[this.current]) {
            this.audio[this.current].playing = true
          }
        }
        backgroundAudioManager.onPlay(res => {
          let item = this.audio[this.current]
          if (!item) {
            return
          }
          item.playing = true
          item.disabledDrag = false
        })
        backgroundAudioManager.onTimeUpdate(res => {
          let item = this.audio[this.current]
          if (!item) {
            return
          }
          if (!item.duration_s) {
            item.duration_s = backgroundAudioManager.duration
            // item.duration = this.calcTime(backgroundAudioManager.duration)
          } else {
            item.duration = this.calcTime(backgroundAudioManager.duration - backgroundAudioManager.currentTime)
          }
          if (!item.dragState) {
            item.progress = Math.ceil(backgroundAudioManager.currentTime * 100 / backgroundAudioManager.duration)
          }
        })
        backgroundAudioManager.onPause(res => {
          let item = this.audio[this.current]
          if (!item) {
            return
          }
          item.playing = false
        })
        backgroundAudioManager.onStop(res => {
          let item = this.audio[this.current]
          if (!item) {
            return
          }
          item.playing = false
          item.disabledDrag = true
        })
        backgroundAudioManager.onEnded(res => {
          if (this.autoplayFlag) {
            if (this.audio.length > this.current + 1) {
              this.playAudio('', this.current + 1)
            }
          }

          let item = this.audio[this.current]
          let that = this
          if (!item) {
            return
          }
          item.progress = 0
          item.playing = false
          item.duration = this.calcTime(item.playtime || 0)
          setTimeout(function () {
            item.duration = that.calcTime(item.playtime || 0)
          }, 200)
        })
      }
    },
    async onLoad (options) {
      await getUnionid()
      Object.assign(this.$data, this.$options.data())

      // 重置参数
      this.current = -1
      this.hideMoreAudio = true
      this.showAudioBuyLayer = false
      this.hideMoreDesc = true

      let {
        id
      } = this.$root.$mp.query

      let scene = decodeURIComponent(options.scene || '')
      let _sence = scene.match(/id=(\d+)/)
      if (_sence && _sence.length > 1) {
        id = _sence[1]
      }

      let _from = scene.replace('?', '').replace(/&id=\d+/, '').replace(/^id=\d+/, '')

      this.from = _from

      reportData({
        funcx: '商品详情-景点',
        keyx: id,
        from: this.from
      })
      this.from = ''
      this.resId = id

      await this.loadData()

      this.initBackAudio()

      dataResArr.push({ ...this.$data })

      let that = this
      wx.getSystemInfo({
        success: function (res) {
          if (res.platform === 'ios') {
            that.isShow = true
          }
        }
      })
    },
    onUnload () {
      dataResArr.pop()
      const dataNum = dataResArr.length
      if (!dataNum) return
      Object.assign(this.$data, dataResArr[dataNum - 1])
    },
    onShow () {
      var that = this
      that.initBackAudio()

      // 简介高度计算
      setTimeout(function () {
        wx.createSelectorQuery().select('#intro_content').boundingClientRect(
          function (rect) {
            if (rect.height >= 96) {
              that.introFold = true
            } else {
              that.introFold = false
            }
          }
        ).exec()
      }, 100)
    }
  }
</script>

<style lang="scss">
  @import './audio.scss';
</style>
